<template>
  <Drawer>
    <!-- 表单 -->
    <BaseForm />
  </Drawer>
</template>

<script lang="ts" setup>
import type { AgentListResp, AgentReq } from '#/api/agent/model/listModel';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { createagent, getAgentlistById, updateagent } from '#/api/agent/list';

import { formColumns } from '../schemas';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
// 表单实例
const AgentFormRef = ref();
// 定义表单
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false, // 不显示操作按钮
  layout: 'vertical',
  schema: formColumns,
});
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  onConfirm: async () => {
    const { type, id } = drawerApi.getData<Record<string, any>>();
    const isPass = (await baseFormApi.validateAndSubmitForm()) as AgentReq; // 校验表单
    if (!isPass) {
      return; // 校验不通过
    } // 验证表单
    if (type === 'addData') {
      addOrEditDictionaryHandle(isPass);
    }
    if (type === 'editData') {
      addOrEditDictionaryHandle(isPass, id);
    }
  },

  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 设置默认值
      const { type, id } = drawerApi.getData<Record<string, any>>();
      // 新增
      if (type === 'addData') {
        await nextTick();
        AgentFormRef.value?.formRef?.resetFields();
        // 确保表单已经挂载;
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getMenuDetailInfo(id);
      }
    } else {
      // 关闭弹窗时重置表单
      AgentFormRef?.value?.formRef?.resetFields();
    }
  },
});

/**
 * @author Buke
 * @description 新增或者编辑
 * @param {Record<string, any>} formData - 表单数据对象。
 * @param {number} id - ID（可选）。
 * @returns {void}
 */
async function addOrEditDictionaryHandle(
  formData: AgentReq,
  id?: number,
): Promise<void> {
  const data = {
    ...formData,
    id,
  };
  id ? await updateagent(data) : await createagent(data);
  ElMessage.success($t('common.operateSuccess'));
  emit('refresh');
}

/**
 * @author Buke
 * @description 详情数据回显
 * @param {number} id - 要回显的客服ID。
 * @returns {void}
 */
async function getMenuDetailInfo(id: any): Promise<void> {
  drawerApi.setState({ loading: true });
  await getAgentlistById(id).then((res: AgentListResp) => {
    baseFormApi.setValues(res);
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  });
}
</script>
